from django import forms
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render, redirect, reverse

from web import models
from web.utils.bootstrap import BootstrapForm
from web.utils.pager import Pagernation
from web.utils.response import BaseResponse


def vendor_list(request):
    keyword = request.GET.get("keyword", "").strip()
    con = Q()
    if keyword:
        con.connector = "OR"
        con.children.append(('title__contains', keyword))

    # 获取所有数据
    queryset = models.Vendor.objects.filter(con)

    pager = Pagernation(request, queryset)

    context = {
        'pager': pager,
        'keyword': keyword
    }
    return render(request, 'vendor_list.html', context)


class VendorModelForm(BootstrapForm, forms.ModelForm):
    class Meta:
        model = models.Vendor
        fields = '__all__'


def vendor_add(request):
    if request.method == 'GET':
        form = VendorModelForm()
        return render(request, 'form.html', {'form': form})
    form = VendorModelForm(data=request.POST)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})
    form.save()
    return redirect(reverse('vendor_list'))



def vendor_edit(request, pk):
    obj = models.Vendor.objects.filter(id=pk).first()
    if request.method == 'GET':
        form = VendorModelForm(instance=obj)
        return render(request, 'form.html', {'form': form})
    form = VendorModelForm(data=request.POST, instance=obj)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})
    form.save()
    return redirect(reverse('vendor_list'))


def vendor_delete(request):
    cid = request.GET.get('cid', 0)
    if not cid:
        res = BaseResponse(status=False, detail='请选择要删除的数据')
        return JsonResponse(res.dict)

    exists = models.Vendor.objects.filter(id=cid).exists()
    if not exists:
        res = BaseResponse(status=False, detail="要删除的数据不存在")
        return JsonResponse(res.dict)
    models.Vendor.objects.filter(id=cid).delete()
    res = BaseResponse(status=True)
    return JsonResponse(res.dict)
